using UnityEngine;
using QFramework;

namespace ProjectMyFarmAndShe
{
	public partial class ShopItemTemplate : ViewController,IController
	{
		private ShopData mData;
		private IToolbarSystem mToolbarSystem;
		
		void Start()
		{
			// Code Here

			mToolbarSystem = this.GetSystem<IToolbarSystem>();
		}

		public void Init(ShopData data)
		{
			mData = data;

			DescriptionText.text = mData.Description;
			CountText.text = mData.Count.ToString();
			PriceText.text = $"价格:{mData.Price}";
			Icon.sprite = ResController.Default.GetToolIconGetKey(mData.Icon);

			mData.Count.RegisterWithInitValue(count =>
				{
					if (count == 0)
					{
						this.DestroyGameObjGracefully();
					}
					
					CountText.text = mData.Count.ToString();
				})
				.UnRegisterWhenGameObjectDestroyed(gameObject);

			Global.Coin.RegisterWithInitValue(coin =>
				{
					if (coin >= mData.Price)
					{
						BtnBuy.interactable = true;
					}
					else
					{
						BtnBuy.interactable = false;
					}
					
				})
				.UnRegisterWhenGameObjectDestroyed(gameObject);
			
			BtnBuy.onClick.AddListener(() =>
			{
				var success = mToolbarSystem.AddToolbarData(mData.Key, 1);
				if (success)
				{
					Global.Coin.Value -= mData.Price;
					mData.Count.Value -= 1;
					MessagePanel.Default.AddMessage($"购买一个{mData.Name},花费{mData.Price}");
					AudioKit.PlaySound("resources://BuyItem");
				}
				else
				{
					MessagePanel.Default.AddMessage($"工具栏满了,无法购买商品");
				}
			});
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}
